package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.core.enums.BorrowerStatusEnum;
import com.atguigu.srb.core.enums.IntegralEnum;
import com.atguigu.srb.core.mapper.*;
import com.atguigu.srb.core.pojo.entity.Borrower;
import com.atguigu.srb.core.pojo.entity.BorrowerAttach;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.entity.UserIntegral;
import com.atguigu.srb.core.pojo.vo.BorrowerApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerAttachVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.pojo.vo.BorrowerVO;
import com.atguigu.srb.core.service.BorrowerService;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-09-13
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {


    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    BorrowerAttachMapper borrowerAttachMapper;
    @Resource
    DictService dictService;
    @Resource
    UserIntegralMapper userIntegralMapper;

    @Override
    public Integer getBorrowerStatusByUserId(String userId) {
        QueryWrapper<Borrower> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        Borrower borrower = baseMapper.selectOne(queryWrapper);
        if (borrower == null){
            return 0;
        }
        return borrower.getStatus();
    }

    @Override
    public void saveBorrower(BorrowerVO borrowerVO, Long userId) {
        //根据userid获得userinfo
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //将数据存入borrower表
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVO,borrower);
        borrower.setUserId(userId);
        borrower.setName(userInfo.getName());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        baseMapper.insert(borrower);
        //将数据保存到borrower_attach
        Long id = borrower.getId();
        List<BorrowerAttach> borrowerAttachList = borrowerVO.getBorrowerAttachList();
        for (BorrowerAttach borrowerAttach : borrowerAttachList){
            borrowerAttach.setBorrowerId(id);
            borrowerAttachMapper.insert(borrowerAttach);
        }
        //更新userinfo表中的认证状态
        userInfo.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        userInfoMapper.updateById(userInfo);

    }

    @Override
    public IPage<Borrower> getListPage(Page<Borrower> borrowerPage, String keyword) {
        QueryWrapper<Borrower> borrowerQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(keyword)){
            borrowerQueryWrapper.like("name",keyword)
                    .or().like("mobile",keyword)
                    .or().like("id_card",keyword);
        }
        Page<Borrower> resultPage = baseMapper.selectPage(borrowerPage, borrowerQueryWrapper);
        return resultPage;
    }

    @Override
    public BorrowerDetailVO show(Long id) {
        BorrowerDetailVO borrowerDetailVO = new BorrowerDetailVO();
        Borrower borrower = baseMapper.selectById(id);
        BeanUtils.copyProperties(borrower,borrowerDetailVO);
        borrowerDetailVO.setStatus(BorrowerStatusEnum.AUTH_RUN.getMsg());
        borrowerDetailVO.setSex(borrower.getSex()==0?"女":"男");
        borrowerDetailVO.setMarry(borrower.getMarry()?"是":"否");

        //集合类型数据处理
        String educationName = dictService.getDictNameByDictCodeAndValueId("education",borrower.getEducation());
        String incomeName = dictService.getDictNameByDictCodeAndValueId("income",borrower.getIncome());
        String industryName = dictService.getDictNameByDictCodeAndValueId("industry",borrower.getIndustry());
        String returnSourceName = dictService.getDictNameByDictCodeAndValueId("returnSource",borrower.getReturnSource());
        String relationName = dictService.getDictNameByDictCodeAndValueId("relation",borrower.getContactsRelation());

        borrowerDetailVO.setEducation(educationName);
        borrowerDetailVO.setIncome(incomeName);
        borrowerDetailVO.setIndustry(industryName);
        borrowerDetailVO.setReturnSource(returnSourceName);
        borrowerDetailVO.setContactsRelation(relationName);

        //附件表数据处理
        List<BorrowerAttachVO> borrowerAttachVOList= new ArrayList<>();
        QueryWrapper<BorrowerAttach> borrowerAttachQueryWrapper = new QueryWrapper<>();
        borrowerAttachQueryWrapper.eq("borrower_id", id);
        List<BorrowerAttach> borrowerAttaches =
                borrowerAttachMapper.selectList(borrowerAttachQueryWrapper);
        //将BorrowerAttach 赋值到BorrowerAttachVO
        //流式打开BorrowerAttach 返回BorrowerAttachVO
        borrowerAttachVOList = borrowerAttaches.stream().map((borrowerAttach -> {
            BorrowerAttachVO borrowerAttachVO = new BorrowerAttachVO();
            BeanUtils.copyProperties(borrowerAttach,borrowerAttachVO);
            return borrowerAttachVO;
        })).collect(Collectors.toList());
        borrowerDetailVO.setBorrowerAttachVOList(borrowerAttachVOList);
        return borrowerDetailVO;
    }

    @Override
    public void approvalSubmit(BorrowerApprovalVO borrowerApprovalVO) {
        Long borrowerId = borrowerApprovalVO.getBorrowerId();
        Borrower borrower = baseMapper.selectById(borrowerId);
        borrower.setStatus(BorrowerStatusEnum.AUTH_OK.getStatus());
        baseMapper.updateById(borrower);

        //user_integral 中新增数据
        BigDecimal sum = new BigDecimal("0");
        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(borrower.getUserId());
        userIntegral.setContent("借款人基本信息");
        userIntegral.setIntegral(borrowerApprovalVO.getInfoIntegral());
        userIntegralMapper.insert(userIntegral);
        sum =sum.add(new BigDecimal(userIntegral.getIntegral()));
        //身份证
        Boolean isIdCardOk = borrowerApprovalVO.getIsIdCardOk();
        if (isIdCardOk){
            userIntegral.setContent(IntegralEnum.BORROWER_IDCARD.getMsg());
            userIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegralMapper.insert(userIntegral);
            sum = sum.add(new BigDecimal(IntegralEnum.BORROWER_IDCARD.getIntegral()));
        }
        //车
        Boolean isCarOk = borrowerApprovalVO.getIsCarOk();
        if (isCarOk){
            userIntegral.setContent(IntegralEnum.BORROWER_CAR.getMsg());
            userIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            userIntegralMapper.insert(userIntegral);
            sum = sum.add(new BigDecimal(IntegralEnum.BORROWER_CAR.getIntegral()));
        }
        //房
        Boolean isHouseOk = borrowerApprovalVO.getIsHouseOk();
        if (isHouseOk){
            userIntegral.setContent(IntegralEnum.BORROWER_HOUSE.getMsg());
            userIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            userIntegralMapper.insert(userIntegral);
            sum = sum.add(new BigDecimal(IntegralEnum.BORROWER_HOUSE.getIntegral()));
        }
        //userinfo表中更新总积分
        Long userId = borrower.getUserId();
        UserInfo userInfo = userInfoMapper.selectById(userId);
        userInfo.setIntegral(sum.intValue());
        userInfo.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_OK.getStatus());
        userInfoMapper.updateById(userInfo);
    }

}
